package knicker.api.servlet.auth;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;


import net.sf.json.JSONObject;

import net.jeremybrooks.knicker.*;
import net.jeremybrooks.knicker.dto.*;

/**
 * Servlet implementation class AuthServlet
 */
public class AuthServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static Authenticator authenticator;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		

				try {
					if(Calendar.getInstance().getTimeInMillis() - Authenticator.getTokenStatus() >= Authenticator.getResetInMillis())
						Authenticator.auth(request.getParameter("apiKey"), request.getParameter("user"), request.getParameter("passwd"));
						User user = AccountApi.user(Authenticator.getAuthToken());
						
						long timeToReset = Calendar.getInstance().getTimeInMillis() - Authenticator.getTokenStatus();
						
						Map<String, String> map = new HashMap<String, String>();
						  
						 map.put("email", user.getEmail());
						 map.put("id",user.getId());
						 map.put("status",user.getStatus());
						 map.put("userName",user.getUserName());
						 map.put("loginTime",Authenticator.getResetInMillis() - timeToReset + "");
	
						 JSONObject obj = new JSONObject();
						 obj.putAll(map);
						  
						 // Write JSON string.
						 response.setContentType("application/json");
						 response.setCharacterEncoding("UTF-8");
						 response.getWriter().write(obj.toString());
					
				} catch (KnickerException e) {
					Map<String, String> map = new HashMap<String, String>();
					  
					 map.put("email", "null");
					 map.put("id","null");
					 map.put("status","1");
					 map.put("userName","null");
					 map.put("loginTime","null");

					 JSONObject obj = new JSONObject();
					 obj.putAll(map);
					  
					 // Write JSON string.
					 response.setContentType("application/json");
					 response.setCharacterEncoding("UTF-8");
					 response.getWriter().write(obj.toString());
				}
	}
}
